use sea_orm_migration::prelude::*;

#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .create_table(
                Table::create()
                    .table(ProductResource::Table)
                    .if_not_exists()
                    .col(
                        ColumnDef::new(ProductResource::Id)
                            .uuid()
                            .not_null()
                            .primary_key(),
                    )
                    .col(ColumnDef::new(ProductResource::ProductId).uuid().not_null())
                    .col(ColumnDef::new(ProductResource::LanguageCode).string().not_null())
                    .col(ColumnDef::new(ProductResource::ResourceId).uuid().not_null())
                    .col(ColumnDef::new(ProductResource::ResourceType).string().not_null())
                    .col(ColumnDef::new(ProductResource::SortOrder).integer().not_null().default(0))
                    .col(ColumnDef::new(ProductResource::CreatedAt).timestamp_with_time_zone().not_null())
                    .col(ColumnDef::new(ProductResource::UpdatedAt).timestamp_with_time_zone().not_null())
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk-product-resource-product-id")
                            .from(ProductResource::Table, ProductResource::ProductId)
                            .to(Product::Table, Product::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .foreign_key(
                        ForeignKey::create()
                            .name("fk-product-resource-resource-id")
                            .from(ProductResource::Table, ProductResource::ResourceId)
                            .to(Resource::Table, Resource::Id)
                            .on_delete(ForeignKeyAction::Cascade),
                    )
                    .index(
                        Index::create()
                            .name("idx-product-resource-product-lang")
                            .col(ProductResource::ProductId)
                            .col(ProductResource::LanguageCode),
                    )
                    .to_owned(),
            )
            .await
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        manager
            .drop_table(Table::drop().table(ProductResource::Table).to_owned())
            .await
    }
}

#[derive(DeriveIden)]
enum ProductResource {
    Table,
    Id,
    ProductId,
    LanguageCode,
    ResourceId,
    ResourceType,
    SortOrder,
    CreatedAt,
    UpdatedAt,
}

#[derive(DeriveIden)]
enum Product {
    Table,
    Id,
}

#[derive(DeriveIden)]
enum Resource {
    Table,
    Id,
}